package cn.benma666.sjsj.ljq.fzgj;

import cn.benma666.crypt.DesUtil;
import cn.benma666.domain.SysQxFwq;
import cn.benma666.exception.BusinessException;
import cn.benma666.exception.MyException;
import cn.benma666.iframe.Conf;
import cn.benma666.iframe.MyParams;
import cn.benma666.iframe.Result;
import cn.benma666.myutils.JVMUtil;
import cn.benma666.myutils.StringUtil;
import cn.benma666.sjsj.web.DefaultLjq;
import com.alibaba.druid.util.Utils;
import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

/**
 * shell命令执行拦截器
 */
public class ShellLjq extends DefaultLjq {
    /**
     * 服务器解密秘钥
     */
    private static final String fwqPassword = Conf.getUtilConfig().getFwqEjmm();

    @Override
    public Result insert(MyParams myParams) {
        JSONObject yobj = myParams.yobj();
        // 执行命令
        String ml = yobj.getString("ml");
        String[] mls = ml.split("\n");
        // 服务器id
        String fwqid = yobj.getString("fwq");
        // 返回结果
        StringBuilder resStr = new StringBuilder();
        try {
            // 如果不是本机
            if (isBlank(fwqid)) {
                String encoding = JVMUtil.getSysEncoding();
                Runtime runtime = Runtime.getRuntime();
                for (String s : mls) {
                    if (!isBlank(s)) {
                        Process process = runtime.exec(s);
                        resStr.append("==================>").append(s).append("\n");
                        resStr.append(new String(Utils.readByteArray(process.getInputStream()), encoding));
                        resStr.append(new String(Utils.readByteArray(process.getErrorStream()), encoding));
                        resStr.append("\n");
                        process.destroy();
                    }
                }
            } else {
                // 查询服务器信息
                SysQxFwq fwq = db().lambdaQuery(SysQxFwq.class).andEq(SysQxFwq::getId, fwqid).singleSimple();
                //Windows默认GBK编码，其他系统采用UTF-8，若将来不能满足就在服务器管理中添加编码配置
                String encoding = "01".equals(fwq.getLx())?"GBK":"UTF-8";
                JSch jsch = new JSch();
                Session session = jsch.getSession(fwq.getYhm(), fwq.getIp(), StringUtil.isBlank(fwq.getYcdk()) ? 22 : Integer.parseInt(fwq.getYcdk()));
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                if (StringUtil.isBlank(fwq.getMm())) {
                    throw new MyException("服务器解密秘钥为空");
                }
                // 解密密码
                String pwd = DesUtil.decrypt(fwq.getMm(), fwqPassword);
                session.setPassword(pwd);
                session.connect(60000);
                ChannelExec process = (ChannelExec) session.openChannel("exec");
                process.setCommand(ml);
                process.connect();
                resStr.append("==================>").append(ml).append("\n");
                resStr.append(new String(Utils.readByteArray(process.getInputStream()), encoding));
                resStr.append(new String(Utils.readByteArray(process.getErrStream()), encoding));
                resStr.append(new String(Utils.readByteArray(process.getExtInputStream()), encoding));
                resStr.append("\n");
                process.disconnect();
            }
        } catch (Exception e) {
            throw new BusinessException("命令执行异常",e);
        }
        JSONObject res = new JSONObject();
        res.put("zxjg", resStr);
//        res.put("ml", "");
        return success("操作成功", res);
    }
}
